<template>
  <div class="app-container">
    <el-form
      label-position="top"
      v-show="state.showSearch"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
    >
      <el-form-item label="公司名称" prop="companyId">
        <ApiSelect
          v-model="queryParams.companyId"
          :api="selectState.company.api"
          :params="selectState.company.params"
          :valueField="selectState.company.valueField"
          :labelField="selectState.company.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="区域名称" prop="areaId">
        <ApiSelect
          :params="{ companyId: queryParams.companyId }"
          v-model="queryParams.areaId"
          :api="selectState.area.api"
          :valueField="selectState.area.valueField"
          :labelField="selectState.area.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="线路名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="线路名称" />
      </el-form-item>
      <el-form-item label="线路负责人" prop="contracts">
        <el-input v-model="queryParams.contracts" placeholder="线路负责人" />
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-select v-model="queryParams.enable" placeholder="请选择" clearable>
          <el-option
            v-for="dict in sys_common_staus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['tissue:route:add']" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList">
      <el-table-column type="selection" width="50" />
      <el-table-column
        label="公司名称"
        align="center"
        prop="companyName"
        :show-overflow-tooltip="true"
        min-width="150"
      />
      <el-table-column label="区域名称" align="center" prop="areaName" min-width="140" />
      <el-table-column label="线路名称" align="center" prop="name" />
      <el-table-column label="点位数量" align="center" prop="positionCount" width="100" />
      <el-table-column label="设备数量" align="center" prop="machineCount" width="100" />
      <el-table-column label="线路负责人" align="center" prop="contactsName" min-width="120" />
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <dict-tag :options="sys_common_staus" :value="row.enable" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" fixed="right" width="150">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleTableAction(row, 'detail')">查看</el-button>
          <el-button
            link
            type="primary"
            v-hasPermi="['tissue:route:edit']"
            @click="handleTableAction(row, 'edit')"
            >编辑</el-button
          >

          <ConfirmButton
            v-hasPermi="['tissue:route:dis']"
            :row="row"
            valueField="enable"
            tipText="此线路"
            @confirm="handleTableAction"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="state.total > 0"
      :total="state.total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      v-model="state.visible"
      :title="state.title"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <AreaDetail
        v-if="state.actionType == 'detail'"
        @close="state.visible = false"
        :routeId="state.detailId"
      />
      <template v-else>
        <el-form
          ref="dialogFormRef"
          :model="dialogFormModel"
          :rules="state.formRules"
          label-position="top"
          :inline="true"
        >
          <el-form-item label="公司名称" prop="companyId">
            <ApiSelect
              v-model="dialogFormModel.companyId"
              :api="selectState.company.api"
              :params="selectState.company.enableParams"
              :valueField="selectState.company.valueField"
              :labelField="selectState.company.labelField"
              :immediate="isEdit"
            />
          </el-form-item>
          <el-form-item label="区域名称" prop="areaId">
            <ApiSelect
              v-model="dialogFormModel.areaId"
              :params="{ companyId: dialogFormModel.companyId, enable: 1 }"
              :api="selectState.area.api"
              :valueField="selectState.area.valueField"
              :labelField="selectState.area.labelField"
              :immediate="isEdit"
              clearable
              @change="onAreaChange"
            />
          </el-form-item>
          <el-form-item label="线路名称" prop="name">
            <el-input v-model="dialogFormModel.name" placeholder="线路名称" />
          </el-form-item>

          <el-form-item label="线路负责人" prop="contracts">
            <ApiSelect
              v-model="dialogFormModel.contracts"
              @change="onContractChange"
              :api="selectState.user.api"
              :params="{
                type: 'route',
                enable: 1,
                companyId: dialogFormModel.companyId,
                cityName: cityName
              }"
              :valueField="selectState.user.valueField"
              :labelField="selectState.user.labelField"
              :immediate="isEdit"
            />
          </el-form-item>
          <el-form-item label="联系方式" prop="mobile">
            <el-input v-model="dialogFormModel.mobile" disabled />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="dialogFormModel.email" disabled />
          </el-form-item>

          <el-form-item label="线路描述" prop="describe">
            <el-input
              style="width: 500px"
              v-model="dialogFormModel.describe"
              maxlength="250"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </el-form>
      </template>

      <template v-if="state.actionType != 'detail'" #footer>
        <el-button @click="handleAction(false)">取消</el-button>
        <el-button type="primary" @click="handleAction(true)">
          {{ state.actionType == 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Area">
import { ElMessage } from 'element-plus'
import { getRouteList, updateRoute, addRoute, disableRoute } from '@/api/organization/route'
import { formRules } from '@/utils/valid/formRules'
import AreaDetail from '../components/areaDetail.vue'
import { useOrganApiConfig } from '@/hooks/service'
import { onMountedOrActivated } from '@/hooks/common'
import { handleUpdConfirm, handleAreaName } from '@/utils/tools'

const selectState = useOrganApiConfig()

const queryRef = ref(null)
const dialogFormRef = ref(null)
const { proxy } = getCurrentInstance()
const { sys_common_staus } = proxy.useDict('sys_common_staus')

const dialogFormModel = ref({})
const state = reactive({
  visible: false,
  actionType: '',
  dialogTitle: '',
  showSearch: true,
  total: 0,
  loading: false,
  operType: '',
  formRules: {
    companyId: formRules.set('请选择', 'change'),
    areaId: formRules.set('请选择', 'change'),
    contracts: formRules.set('请选择', 'change'),
    name: formRules.maxStr
  },
  detailId: ''
})
const isEdit = computed(() => state.actionType == 'edit')
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
const tableList = ref([])
const cityName = ref('')

function onAreaChange(ev, item) {
  console.log({ item })
  cityName.value = item.name ? item.name.split('/')[0] : ''

  console.log(cityName.value)
}
function handleSearch(confirm) {
  if (!confirm) queryRef.value.resetFields()

  queryParams.value.pageNum = 1
  getList()
}

async function getList() {
  state.loading = true

  try {
    const r = await getRouteList(queryParams.value)
    tableList.value = r?.rows
    state.total = r?.total || 0
  } finally {
    state.loading = false
  }
}

/**table Action */
function handleAdd() {
  handleTableAction({}, 'add')
}
function handleTableAction(obj, operType) {
  state.operType = operType
  if (operType == 'auth') {
    disableRoute({ id: obj.routeId, enabled: obj.enable }).then(() => {
      ElMessage.success('操作成功')

      getList()
    })
  } else {
    state.actionType = operType
    state.visible = true
    if (operType == 'detail') {
      state.detailId = obj.routeId
    } else {
      if (operType == 'edit') {
        dialogFormModel.value = { ...obj, contracts: +obj.contracts }
        cityName.value = dialogFormModel.value.areaName.split('/')[0]
        console.log(operType, dialogFormModel.value)
      }
    }
  }
}

/**dialog form */
function handleAction(confirm) {
  if (confirm) {
    dialogFormRef.value?.validate((valid) => {
      if (valid) {
        const isAdd = state.operType == 'add'
        handleUpdConfirm(isAdd, '确认要修改当前线路？').then(async () => {
          const fetchMethod = isAdd ? addRoute : updateRoute
          fetchMethod(dialogFormModel.value).then((r) => {
            ElMessage.success(isAdd ? '新增成功' : '更新成功')

            getList()
            state.visible = false
          })
        })
      }
    })
  } else {
    state.visible = false
  }
}

watch(
  () => state.visible,
  (v) => {
    if (!v)
      nextTick(() => {
        dialogFormModel.value = {}
      })
  }
)

function onContractChange(_, option = {}) {
  dialogFormModel.value.mobile = option?.phonenumber
  dialogFormModel.value.email = option?.email
}

/**init +  onActivated*/
onMountedOrActivated(getList)
</script>
